<template>
    <view>
        <view>
            <form @submit="onSubmit(true, $event)" v-if="loginMethod === 'quick'" class="flex flex-column flex-center">
                <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                    <image class="avatar"
                           :src="formData.avatarUrl?formData.avatarUrl:'https://qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'">
                    </image>
                    <text class="loginLogoText" v-if="isShow">授权头像</text>
                </button>
                <view class="nameContent">
                    <view class="title">昵称</view>
                    <!-- 添加 @focus 事件 -->
                    <input name="username"  type="nickname" placeholder="请填写昵称" class="weui-input"
                           v-model="formData.username" />
						  
                </view>
                <view style="width: 80%;margin-left: 9%;">
                    <u-button type="primary" shape="circle" text="一键登录" @tap="uniLogin"></u-button>
                    <view class="margin-top"></view>
                    <u-button type="info" shape="circle" @tap="changeLoginMethod('password')" text="其他登录方式"></u-button>
                </view>
            </form>

            <!-- 其他登录方式 -->
            <view v-else class="flex flex-row flex-center ">
                <view style="width: 80%;margin-top: 150px;">
                    <u--input prefixIcon="account-fill" shape='circle' prefixIconStyle="font-size: 22px;color: #909399"
                              placeholder="请输入用户名" border="surround"  v-model="username"></u--input>
                    <view class="margin-top"></view>
                    <u--input prefixIcon="eye-fill" prefixIconStyle="font-size: 22px;color: #909399" placeholder="请输入密码"
                              border="surround" type='password' shape='circle' v-model="password"></u--input>
                    <view class="margin-top"></view>
                    <u-button type="primary" shape="circle" text="使用账号密码登录" @click="passwordLogin"></u-button>
                    <view class="margin-top"></view>
                    <u-button type="info" shape="circle" @tap="changeLoginMethod('quick')" text="微信一键登录"></u-button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            userId: "",
            formData: {
                username: '',
                avatarUrl: '',
                password: ''
            },
            isShow: true,
            loginMethod: 'quick', // 新增一个属性来标识当前的登录方式，默认是一键登录
            username: '',
            password: ''
        };
    },
    computed: {},
    watch: {
        formData: {
            handler(newVal, oldValue) {
                if (newVal.avatarUrl) {
                    this.isShow = false; // 监测isShow，如果授权头像了就隐藏 授权头像 字样
                }
            },
            deep: true,
            immediate: true
        },
		

    },
    onLoad() {
		
    },
    methods: {
        // 获取微信头像
        onChooseAvatar(e) {
            this.formData.avatarUrl = e.detail.avatarUrl;
        },
		
        // 切换登录方式
        changeLoginMethod(method) {
            this.loginMethod = method;
        },
        uniLogin() {
            uni.login({
                provider: 'weixin',
                success: (loginRes) => {
                    this.loginWithCode(loginRes.code);
                    console.log("微信用户信息",loginRes.code)
                },
                fail: (error) => {
                    this.loginError = '微信登录失败: ' + error.errMsg;
                }
            });
        },
        passwordLogin() {
            uni.request({
                url: 'http://localhost:8090/user/usernameLogin',
                method: 'POST',
                data: JSON.stringify({
                    username: this.username,
                    password: this.password
                }),
                header: {
                    'Content-Type': 'application/json',
                },
                success: (res) => {
                  
					// console.log(res.data)
                    if (res.data.code == 200) {
                        uni.setStorageSync('userId', res.data.data.userId);
                        this.hasUserInfo = true;
                        uni.showToast({
                            title: '登录成功',
                            icon: 'success',
                            duration: 2000
                        });
                        uni.reLaunch({
                            url: '/pages/my/my'
                        })
                    } else {
                        uni.showToast({
                            title: '账号或密码错误，请重新输入',
                            icon: 'fail',
                            duration: 2000
                        });
                        this.loginError = res.data.msg;
                    }
                },
                fail: (error) => {
                    this.loginError = '请求登录接口失败：' + error.errMsg;
                }
            });
        },
        loginWithCode(code) {
            uni.request({
                url: 'http://localhost:8090/user/login',
                method: 'GET',
                data: {
                    code: code,
                    avatarUrl: this.formData.avatarUrl,
                    username: this.formData.username
                },
                header: {
                    'Content-Type': 'application/json',
                },
                success: (res) => {
					console.log(res.data)
                    if (res.data.code == 200) {
                        uni.setStorageSync('userId', res.data.data.user.userId);
                        this.hasUserInfo = true;
                        uni.showToast({
                            title: '登录成功',
                            icon: 'success',
                            duration: 2000
                        });

                        uni.reLaunch({
                            url: '/pages/my/my'
                        })
                    } else {
                        this.loginError = res.data.msg;
                    }
                },
                fail: (error) => {
                    this.loginError = '请求登录接口失败：' + error.errMsg;
                }
            });
        },
        onSubmit(isSubmit, event) {
            // console.log("用户数据",event)
            event.preventDefault();
            if (isSubmit) {
                this.uniLogin();
            } else {
                this.passwordLogin();
            }
        },
       
    }
};
</script>

<style scoped lang="scss">
.avatar-wrapper {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: none;
    color: inherit;
    border: none;
    padding: 0;
    font: inherit;
    cursor: pointer;
    outline: inherit;

    .avatar {
        height: 120rpx;
        width: 120rpx;
        border-radius: 20rpx;
    }
}

.avatar-wrapper::after {
    border: none;
}

.nameContent {
    display: flex;
    margin: 70rpx 0;
    border-top: 1px solid #eee;
    border-bottom: 2rpx solid #eee;
    padding: 20rpx 40rpx;
    width: 100vw;
    box-sizing: border-box;
    font-size: 28rpx;
    align-items: center;

    .title {
        margin-right: 40rpx;
    }
}
</style>